var map, tb, navToolbar;

require(["esri/map", "esri/toolbars/navigation", "esri/dijit/HomeButton", "esri/dijit/Scalebar", "esri/dijit/OverviewMap", "esri/toolbars/draw", "dojo/dom", "dojo/on", "dojo/_base/connect", "esri/layers/ArcGISTiledMapServiceLayer", "esri/layers/ArcGISDynamicMapServiceLayer", "myModules/customoperation", "myModules/draw", "myModules/drawOperSite", "agsjs/dijit/TOC", "esri/dijit/InfoWindowLite", "dojo/dom-construct", "dijit/Dialog", "dojo/domReady!"], function(Map, Navigation, HomeButton, Scalebar, OverviewMap, Draw, dom, on, connect, ArcGISTiledMapServiceLayer, ArcGISDynamicMapServiceLayer, customoperation, draw, drawOperSite, TOC, InfoWindowLite, domConstruct, Dialog) {
    map = new Map("mapDiv", {
        logo : false
    });
    //nav tool bar
    navToolbar = new Navigation(map);
    dojo.connect(navToolbar, "onExtentHistoryChange", function() {
        dojo.byId("toolbar.zoomprevious").disabled = navToolbar.isFirstExtent();
        dojo.byId("toolbar.zoomnext").disabled = navToolbar.isLastExtent();
    });

    var myTiledMapServiceLayer = new ArcGISTiledMapServiceLayer("http://192.168.0.203:6080/arcgis/rest/services/xinan/MapServer");
    var dynaLayer = new ArcGISDynamicMapServiceLayer("http://192.168.0.203:6080/arcgis/rest/services/layers/MapServer", {
        opacity : 0.8
    });
    map.on('layers-add-result', function(evt) {
        // overwrite the default visibility of service.
        // TOC will honor the overwritten value.
        // dynaLayer.setVisibleLayers([2, 5, 8, 11]);
        //try {
        toc = new TOC({
            map : map,
            layerInfos : [{
                layer : dynaLayer,
                title : "河流"
                //collapsed: false, // whether this root layer should be collapsed initially, default false.
                //slider: false // whether to display a transparency slider.
            }]
        }, 'layerinfo');
        toc.startup();
        toc.on('load', function() {
            // if (console)
                // console.log('TOC loaded');
            // dom.byId("ChangeFeatureRenderer").disabled = false;
            // dom.byId("SetVisibleLayersProgramatically").disabled = false;
            // dom.byId("FindNodeByLayer").disabled = false;
            // dom.byId("InsertNewLayer").disabled = false;
        });
        //} catch (e) {  alert(e); }
    });

    map.addLayers([myTiledMapServiceLayer, dynaLayer]);
    // 添加地图
    // map.on("load", initToolbar);

    // home 键
        // var home = new HomeButton({
            // map : map
        // }, "HomeButton");
        // home.startup();

    // 比例尺
    var scalebar = new Scalebar({
        map : map,
        attachTo : "bottom-left",
        scalebarUnit : "dual"
    });

    // 鹰眼
    var overviewMapDijit = new OverviewMap({
        map : map,
        attachTo : "bottom-right"
    });
    overviewMapDijit.startup();

    var infoWindow = new InfoWindowLite(null, domConstruct.create("div", null, null, map.root));
    infoWindow.startup();
    map.setInfoWindow(infoWindow);

    // dojo.connect(map, "onClick", function(evt) {
    // mapDlg = new Dialog({
    // title:"test dialog",
    // content:"test content",
    // style: "width: 300px"
    // });
    // mapDlg.show();
    // });
    var tb = new Draw(map);
    var mouseStatOverLink, mouseStatOutLink, graphicClickLink;
    //点击info时激活画图工具
    on(dom.byId("info"), "click", function(evt) {
        if (evt.target.id === "editCtl") {
            if (dom.byId("editCtl").innerHTML == "开始编辑") {
                dom.byId("editCtl").innerHTML = "停止编辑";

                dojo.query("#info button:not([id = 'editCtl'])").forEach(function(node) {
                    node.disabled = false;
                });
                map.setMapCursor("crosshair");
                draw.startEdit(map, tb);

                //绘图时取消图元的点击事件
                dojo.disconnect(mouseStatOverLink);
                dojo.disconnect(mouseStatOutLink);
                dojo.disconnect(graphicClickLink);
            } else {
                dom.byId("editCtl").innerHTML = "开始编辑";
                dojo.query("#info button:not([id = 'editCtl'])").forEach(function(node) {
                    node.disabled = true;
                });
                map.setMapCursor("default");
                draw.stopEdit(map, tb);

                //结束绘图后注册鼠标事件
                mouseStatOverLink = dojo.connect(map.graphics, "onMouseOver", function(event) {
                    map.setMapCursor("pointer");

                });
                mouseStatOutLink = dojo.connect(map.graphics, "onMouseOut", function(event) {
                    map.setMapCursor("default");

                });
                graphicClickLink = dojo.connect(map.graphics, "onClick", clickgraphic);
            }
        } else {
            if (dom.byId("editCtl").innerHTML == "停止编辑") {
                draw.initToolbar(map, tb, evt);
            }
        }
    });

    connect.connect(map, "onLoad", function() {
        map.graphics.enableMouseEvents();
        //鼠标控制
        mouseStatOverLink = dojo.connect(map.graphics, "onMouseOver", function(event) {
            map.setMapCursor("pointer");

        });
        mouseStatOutLink = dojo.connect(map.graphics, "onMouseOut", function(event) {
            map.setMapCursor("default");

        });
        var d = new drawOperSite();
        d.draw(map);
        graphicClickLink = dojo.connect(map.graphics, "onClick", clickgraphic);

        dojo.query("#info button:not([id = 'editCtl'])").forEach(function(node) {
            node.disabled = true;
        });

        dojo.connect(dojo.byId("saveEdit"), "click", function(event) {
            d.save(map);
        });

    });

    function clickgraphic(evt) {
        var extentGeom = pointToExtent(map, evt.mapPoint, 10);
        var filteredGraphics = dojo.filter(map.graphics.graphics, function(graphic) {
            return extentGeom.contains(graphic.geometry);
        });

        var content = "";

        //Build a table containing a row for each feature found
        //选中一个graphic时才弹出信息
        if (filteredGraphics.length == 1) {
            //dojo.forEach(filteredGraphics, function(item) {
            content += "作业点名称：";
            content += filteredGraphics[0].attributes["Name"];
            //});

            map.infoWindow.setContent(content);
            map.infoWindow.setTitle("作业点详情");
            map.infoWindow.show(evt.screenPoint, map.getInfoWindowAnchor(evt.screenPoint));
        }
    }

    function pointToExtent(map, point, toleranceInPixel) {
        //calculate map coords represented per pixel
        var pixelWidth = map.extent.getWidth() / map.width;
        //calculate map coords for tolerance in pixel
        var toleraceInMapCoords = toleranceInPixel * pixelWidth;
        //calculate & return computed extent
        return new esri.geometry.Extent(point.x - toleraceInMapCoords, point.y - toleraceInMapCoords, point.x + toleraceInMapCoords, point.y + toleraceInMapCoords, map.spatialReference);
    }

});
